import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/components/bigfontchoosebutton.dart';
import 'package:dio/dio.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/category/outfitcategory.dart';
import 'package:flutter/cupertino.dart';
import 'package:wayofdressing/good_method/formatDate.dart';
import 'package:wayofdressing/dio/ScheduleDio.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';
import 'package:wayofdressing/vivo_connect.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';

class AddScheduleScreen extends StatefulWidget {
  const AddScheduleScreen({super.key});

  @override
  State<AddScheduleScreen> createState() => _AddScheduleScreenState();
}

class _AddScheduleScreenState extends State<AddScheduleScreen> {
  int whoisactive1 = 1;
  int whoisactive2 = 1;
  DateTime selectedDate = DateTime.now();
  bool isSelected=false;
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void dispose() {
    // TODO: implement dispose
    _descriptionController.dispose();
    super.dispose();
  }
  _cupertinoPicker(){
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.now(), //起始日期
      maxDateTime: DateTime.parse('2025-12-31'), //终止日期
      initialDateTime: selectedDate, //当前日期
      dateFormat: 'yyyy-MMMM-dd',  //显示格式
      locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onChange: (dateTime, List<int> index) { //改变的时候
        setState(() {
          selectedDate = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) { //确定的时候
        setState(() {
          isSelected=true;
          selectedDate = dateTime;
        });
      },
    );
  }
  void _addSchedule() async {
    if (isSelected) {
      try {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        int userId = prefs.getInt('id') ?? 0;
        Response<dynamic> response = await addScheduleByUserIdAndName(
          userId: userId,
          scheduleData: {
            'content': _descriptionController.text,
            'date': formatDate(selectedDate),
          },
          dio: dio,
          outfitName: outfitNumbers[outfits[whoisactive1]]![whoisactive2],
        );
        if (response.statusCode == 200) {
          int scheduleId=response.data['data'];
          _getAiSuggestionAndPost(_descriptionController.text,scheduleId);
          ShowDialog.showCorrect(context);
          _descriptionController.clear();
        } else {
          ShowDialog.showError(context);
          print('日程添加失败');
        }
      } catch (e) {
        ShowDialog.showError(context);
        print('添加日程出现异常：$e');
      }
    }
    else{
      ShowDialog.showErrorAndDetail(context, '请选择时间');
    }
  }
  Future<void> _getAiSuggestionAndPost(String prompt,int id) async {
    final aiSuggestion = await vivogpt('这是一段用户的日常出行内容,请你根据内容给出穿搭建议,详细到品牌种类材质等等,越详细越好:$prompt');
    addAiSuggestionToScheduleById(id: id, aiSuggestion: aiSuggestion, dio: dio);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 40.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              SizedBox(
                height: 50,
              ),
              GestureDetector(
                onTap: (){_cupertinoPicker();},
                child: Container(
                  height: 48,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                        spreadRadius: 2, // 阴影扩展半径
                        blurRadius: 5, // 阴影模糊半径
                        offset: Offset(0, 5), // 阴影偏移量
                      ),
                    ],
                    borderRadius: BorderRadius.circular(25),
                  ),
                  child: Center(
                    child: Text(
                      isSelected?formatDate(selectedDate):'选择时间',
                      style: TextStyle(fontSize: 28),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Container(
                    height: 56,
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                          spreadRadius: 2, // 阴影扩展半径
                          blurRadius: 5, // 阴影模糊半径
                          offset: Offset(0, 5), // 阴影偏移量
                        ),
                      ],
                      borderRadius: BorderRadius.circular(25),
                      color: Colors.white,
                    ),
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: outfitNumbers.length,
                      itemBuilder: (context, index) {
                        return BigFontChooseButton(
                          isActive: whoisactive1,
                          text: outfits[index],
                          listNumber: index,
                          onPressed: () {
                            setState(() {
                              whoisactive1 = index;
                              whoisactive2 = 0;
                            });
                          },
                        );
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 10),
                    height: 56,
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                          spreadRadius: 2, // 阴影扩展半径
                          blurRadius: 5, // 阴影模糊半径
                          offset: Offset(0, 5), // 阴影偏移量
                        ),
                      ],
                      borderRadius: BorderRadius.circular(25),
                      color: Colors.white,
                    ),
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: outfitNumbers[outfits[whoisactive1]]?.length,
                      itemBuilder: (context, index) {
                        return BigFontChooseButton(
                          isActive: whoisactive2,
                          text: outfitNumbers[outfits[whoisactive1]]![index],
                          listNumber: index,
                          onPressed: () {
                            setState(() {
                              whoisactive2 = index;
                            });
                          },
                        );
                      },
                    ),
                  ),
                  Container(
                    height: 56,
                    child: TextField(
                      controller: _descriptionController,
                      decoration: InputDecoration(
                        labelText: '日程内容',
                        labelStyle: TextStyle(fontSize: 20, color: Colors.grey),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(25.0),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(25.0),
                          borderSide: BorderSide(width: 2, color: Colors.grey),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(25.0),
                          borderSide: BorderSide(width: 2, color: Colors.black),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    height: 56,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25), // 圆角半径
                      border: Border.all(
                        // 边框
                        color: Colors.black54, // 边框颜色
                        width: 2, // 边框宽度
                      ),
                    ),
                    child: TextButton(
                      child: Text(
                        '添加',
                        style: TextStyle(color: Colors.black54, fontSize: 28),
                      ),
                      onPressed: _addSchedule,
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 50,
              )
            ],
          ),
        ),
      ),
    );
  }
}
